import type { Formula } from "@/types/formula";
import fs from "fs/promises";

let highestVer: string, highestVal = 0

await fs.readdir("extract/").then(files => {
  files.map(file => {
    // file name like 1.1.4.jar
    const ver = file.split(".").slice(0, 3).reduce((a, b) => a * 1 + parseInt(b) * 1, 0)
    if (ver > highestVal) {
      highestVal = ver
      highestVer = file.replace(".jar", "")
    }
  })
})

export default async function useRelatedFormula(id: string, ver?: string) {
  let res = {
    type: null,
  } as unknown as Formula;

  const FinalVer = ver || highestVer

  const BasicExtraPath = `./extract/${FinalVer}/formula`;
  const extractPath = `${BasicExtraPath}/${id}.json`;
  const cacheExtractPath = `./.cache/extract/temp/${FinalVer}/data/providencraft/recipes/${id}.json`;

  // first try open extract
  try {
    res = JSON.parse(await fs.readFile(extractPath, "utf-8"));
  } catch (e) {
    // second try open cache
    try {
      res = JSON.parse(await fs.readFile(cacheExtractPath, "utf-8"));
      await fs.mkdir(BasicExtraPath, { recursive: true });
      await fs.writeFile(extractPath, JSON.stringify(res, null, 2));
    } catch (e) {
      console.log(e);
    }
  }

  return res
}
